import re
import os
import sys

from core.utils.file_utils import get_current_file_path, get_config_path, paste_path
from core.utils.data_utils import load_yaml, walk_apk_dir

def clean_for_adb(filename):
    """
    清理文件名中的字符，确保在 ADB 操作中安全

    参数:
    filename -- 要处理的文件名

    返回:
    安全文件名 (移除 ADB 和命令行中可能导致问题的字符)
    """
    # 定义 ADB 中可能引起问题的特殊字符集
    # 包括: & | ; > < $ * ? ` ( ) [ ] { } ' " \ ! ~ % # @
    adb_problem_chars = r'+\&\|;><\$\*\?`\(\)\[\]\{\}\'"\\\!\~\%\#\@'

    # 先替换空格为下划线
    clean_name = filename.replace(' ', '_')

    # 替换所有可能引起 ADB 或命令行问题的字符
    clean_name = re.sub(f'[{adb_problem_chars}]', '_', clean_name)

    # 额外处理：将开头的 - 替换为 _（避免被解释为参数）
    if clean_name.startswith('-'):
        clean_name = '_' + clean_name[1:]

    # 替换连续下划线
    clean_name = re.sub(r'_+', '_', clean_name)

    # 移除首尾多余的下划线
    clean_name = clean_name.strip('_')

    # 确保名称非空
    if not clean_name:
        return 'adb_safe_name'

    return clean_name

def safe_rename(old_path, new_name_base):
    """
    安全地重命名文件/文件夹，避免冲突
    """
    # 获取父目录
    dirname = os.path.dirname(old_path)

    # 处理文件扩展名
    if os.path.isfile(old_path):
        basename, extension = os.path.splitext(new_name_base)

        # 只清理文件名部分，保留扩展名原样
        clean_basename = clean_for_adb(basename)
        clean_extension = extension  # 扩展名通常不需要清理

        new_name = clean_basename + clean_extension
        new_path = os.path.join(dirname, new_name)
    else:
        # 处理目录名（无扩展名）
        new_name = clean_for_adb(new_name_base)
        new_path = os.path.join(dirname, new_name)

    # 避免自我重命名
    if new_path == old_path:
        return old_path

    # 处理名称冲突
    counter = 1
    original_new_path = new_path
    while os.path.exists(new_path):
        # 添加序号后缀
        name, ext = os.path.splitext(original_new_path)
        new_path = f"{name}_{counter}{ext}"
        counter += 1

    # 执行重命名
    try:
        os.rename(old_path, new_path)
        return new_path
    except OSError as e:
        print(f"重命名失败: {old_path} → {new_path} ({e})")
        return old_path

def process_path(root_path, lbl_status):
    """
    递归处理所有文件和目录
    """
    # 首先处理深层内容（从深到浅）
    renamed_count = 0

    # 使用 os.walk 深度优先遍历（从深到浅）
    all_paths = []
    for root, dirs, files in os.walk(root_path, topdown=False):
        # 添加文件
        for file in files:
            file_path = os.path.join(root, file)
            all_paths.append(file_path)

        # 添加目录
        for dir_name in dirs:
            dir_path = os.path.join(root, dir_name)
            all_paths.append(dir_path)

    # 处理所有路径（从深到浅）
    for path in reversed(all_paths):
        if os.path.exists(path):  # 检查路径仍然存在
            base_name = os.path.basename(path)
            if not base_name:  # 跳过无效路径
                continue

            # 获取新路径
            new_path = safe_rename(path, base_name)

            if new_path != path:
                # print(f"重命名: {path} → {new_path}")
                renamed_count += 1

    lbl_status.setText(f"\n预处理完成")
    # print(f"\n完成! 共重命名 {renamed_count} 个项目")

def init_file(lbl_status):
    """初始化文件"""
    current_dir = get_current_file_path()
    config_path = os.path.join(current_dir, 'config/data.yaml')
    data_config = load_yaml(config_path)

    test_apk_path = os.path.join(current_dir, data_config['TestApkPath'])
    other_apk_path = os.path.join(current_dir, data_config['OtherApkPath'])
    process_path(test_apk_path, lbl_status)
    process_path(other_apk_path, lbl_status)



